package com.zqq.demo.camera

import android.graphics.ImageFormat
import android.hardware.Camera
import android.view.SurfaceHolder
import com.zqq.base.BaseActivity
import com.zqq.base.BaseViewModel
import com.zqq.base.utils.LogUtils
import com.zqq.demo.R
import com.zqq.demo.databinding.ActivityCameraBinding
import java.io.IOException


class CameraActivity:BaseActivity<BaseViewModel,ActivityCameraBinding>(), Camera.PreviewCallback,
    SurfaceHolder.Callback {

    var mCamera: Camera? = null
    var h264Saver: H264Saver? = null
    var width = 1280
    var height = 720

    override fun setContentViewId(): Int = R.layout.activity_camera

    override fun init() {
        viewBinding.surfaceView.holder.addCallback(this)


        AudioRecordManager.getInstance(this).initAudioCodec()
        AudioRecordManager.getInstance(this).start()

        h264Saver = H264Saver(this, width, height, 0)
        h264Saver?.init()
    }

    private fun openCamera(holder: SurfaceHolder) {

        try {
            mCamera = Camera.open()
            val params = mCamera!!.getParameters()
            params.setPreviewSize(1280, 720)
            params.previewFormat = ImageFormat.NV21
            mCamera!!.setParameters(params)
            mCamera!!.setPreviewDisplay(holder)
            mCamera!!.setPreviewCallbackWithBuffer(this)

            val buffer = ByteArray(1280 * 720 * 3 / 2)
            mCamera!!.addCallbackBuffer(buffer)
            mCamera!!.startPreview()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        h264Saver?.onVideoStop()
        releaseCamera()
    }

    private fun releaseCamera() {
        mCamera?.let {
            it.stopPreview()
            it.release()
        }
        mCamera = null
    }

    override fun onPreviewFrame(p0: ByteArray?, p1: Camera?) {
//        LogUtils.i("bl_camera","onPreviewFrame>>${p0}")
        h264Saver?.onVideo(p0)
        p1?.addCallbackBuffer(p0!!)
    }

    override fun surfaceCreated(p0: SurfaceHolder) {
        openCamera(p0)
    }

    override fun surfaceChanged(p0: SurfaceHolder, p1: Int, p2: Int, p3: Int) {

    }

    override fun surfaceDestroyed(p0: SurfaceHolder) {

    }
}